package com.Bigbluebook.Activity;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.Bigbluebook.R;
import com.Bigbluebook.Service.UserApiService;
import com.Bigbluebook.entity.User;
import com.Bigbluebook.http.PermissionUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    EditText username;
    EditText password;

    Button login;
    Button register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //请求权限
        PermissionUtils.requestInternetPermission(this);
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        login = findViewById(R.id.login);
        register = findViewById(R.id.register);

        // 登录事件
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 隐藏软键盘
                View focusView = getCurrentFocus();
                if (focusView != null) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(focusView.getWindowToken(), 0);
                    }
                }

                // 需要获取的输入的用户名和密码
                String usernameText = username.getText().toString().trim();
                String passwordText = password.getText().toString().trim();

                // 判空检查
                if (usernameText.isEmpty() || passwordText.isEmpty()) {
                    Toast.makeText(MainActivity.this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 显示加载指示器
                ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage("正在登录...");
                progressDialog.show();

                // 创建User对象
                User user = new User(usernameText, passwordText);

                // 使用UserApiService来发送登录请求
                UserApiService userApiService = new UserApiService();
                userApiService.loginUser(user, new Callback<User>() {
                    @Override
                    public void onResponse(Call<User> call, Response<User> response) {
                        // 隐藏加载指示器
                        progressDialog.dismiss();

                        if (response.isSuccessful()) {
                            // 在控制台打印返回的状态码和数据
                            Log.d("LoginResponse", "Status code: " + response.code());
                            User loggedInUser = response.body();
                            if (loggedInUser != null) {
                                Log.d("LoginResponse", "User: " + loggedInUser.toString());
                                Toast.makeText(getApplicationContext(), "登录成功：" + loggedInUser.getUsername(), Toast.LENGTH_SHORT).show();

                                // 用SharedPreferences来存储用户信息
                                SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putString("username", loggedInUser.getUsername());
                                editor.putInt("userid", loggedInUser.getId());
                                editor.commit();

                                // 跳转到主活动
                                Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                                startActivity(intent);
                                finish();
                            } else {
                                Toast.makeText(MainActivity.this, "服务器未返回用户信息", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            // 服务器返回错误响应
                            Toast.makeText(MainActivity.this, "登录失败：" + response.message(), Toast.LENGTH_SHORT).show();
                            Log.d("LoginResponse", "Error message: " + response.message());
                            //startActivity(new Intent(MainActivity.this,HomeActivity.class));
                        }
                    }

                    @Override
                    public void onFailure(Call<User> call, Throwable t) {
                        // 隐藏加载指示器
                        progressDialog.dismiss();

                        // 登录失败的响应
                        Toast.makeText(getApplicationContext(), "登录失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.d("LoginError", "Error: " + t.getMessage());
                    }
                });
            }
        });

        // 注册事件
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //实现界面跳转，从登录界面跳转到注册界面
                Intent intent = null;  //这个变量初始申明为空
                intent = new Intent(MainActivity.this, RegisterActivity.class);//跳转界面
                startActivity(intent);
            }
        });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 处理权限请求结果
        PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}